<template>
  <view>
    <Navbar></Navbar>
    <view class="u-form-box u-m-30">
      <u-form :model="form" label-width="auto" ref="uForm">
        <u-form-item  label="头像">
          <view class="u-flex u-row-right">
            <u-upload :file-list="isEdit ? headImgFileList : undefined" :action="actionOss" :show-progress="false"
              :max-count="1" :del-bg-color="'#51C06A'" image-mode="aspectFit" width="120" height="120"
              @on-success="onHeadSuccess" @on-remove="onHeadRemove" :before-upload="onBeforeUpload"></u-upload>
          </view>
        </u-form-item>
        <u-form-item required="true" label="姓名">
          <u-input placeholder="请填写真实姓名" input-align="right" v-model="form.name" :clearable="false" />
        </u-form-item>
        <u-form-item required="true" label="手机号码">
          <view class="u-text-right">
            <view class="u-flex" v-if="[0].includes(isEdit)">
              <view class="country_code" @click="codeShow = true">
                <text class="u-p-r-10">+{{ form.area_code }}</text>
                <u-icon name="arrow-right" size="26" color="#c0c4cc"></u-icon>
              </view>
              <button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" id="mobile_btn"
                :class="form.mobile ? '' : 'u-color-placeholder'">
                {{ form.mobile || '点击快速获取手机号' }}
              </button>
            </view>
            <view v-else>
              <span class="u-m-r-10" v-if="form.area_code">+{{ form.area_code }} </span>
              <span>{{ form.mobile }}</span>
            </view>
          </view>
        </u-form-item>
        <u-form-item required="true" label="城市">
          <view class="u-text-right" :class="form.hometown ? '' : 'u-color-placeholder'" @click="openHomeTown">
            {{ form.hometown || '请选择常驻城市 >' }}
          </view>
        </u-form-item>
        <u-form-item  label="地址">
          <view class="u-text-right" :class="form.address ? '' : 'u-color-placeholder'" @click="handleGetLocation">
            {{ form.address || '请选择详细地址 >' }}
          </view>
        </u-form-item>
      </u-form>
    </view>

    <!-- 注册协议 -->
    <view class="u-m-t-20 u-flex u-row-center" v-if="isEdit == 0">
      <u-checkbox-group :active-color="'#B3723E'">
        <u-checkbox v-model="agreement" shape="circle">
          <text class="u-tips-color u-font-24">我已阅读并同意</text>
          <text @click.native.stop="goAgrement(1)" class="u-color-puce u-font-24">《用户协议》</text>
          <text @click.native.stop="goAgrement(2)" class="u-color-puce u-font-24">《隐私协议》</text>
        </u-checkbox>
      </u-checkbox-group>
    </view>

    <view style="height: 200rpx;"></view>

    <Bottom :isTwice="true" :rightText="btnText" @confirm="confirm"></Bottom>

    <!-- 区号 -->
    <view v-if="codeShow">
      <u-select v-model="codeShow" @confirm="codeConfirm" :default-value="[0]" :mask-close-able="false"
        value-name="area_code" :list="codeList"></u-select>
    </view>


    <!-- 行业 -->
    <IndustryPopup :showIndustry="industryShow" :classAIndustryObj="classAIndustryObj"
      :classBIndustryList="classBIndustryList" :classAIndustryList="classAIndustryList" @checkA="handleCheckClassA"
      @closes="handleClosePopup"></IndustryPopup>

    <!-- 籍贯 -->
    <UniAddressSelector v-if="showUniAddressSelector" :selectAreaLevelLimit="3" :isSZ="0" @cancel="handleCancel"
      @confirm="handleConfirmArea"></UniAddressSelector>

    <!-- 引导签约公司 -->
    <Modal :show="modal.show" :confirmText="modal.confirmText" :cancelText="modal.cancelText"
      :modalContent="modal.content" :showCancel="modal.showCancel" @cancel="modalCancel" @confirm="modalConfirm">
    </Modal>

    <!-- 通用单选 -->
    <CommonPopup :popupShow="commonPopupData.show" :list="commonPopupData.list" @popupClose="commonPopupData.show = false"
      @onChooseLabel="handleChooseLabel"></CommonPopup>
  </view>
</template>

<script>
import Navbar from '@/components/Navbar'
import Bottom from '@/components/Bottom.vue'
import IndustryPopup from '@/components/IndustryPopup.vue'
import UniAddressSelector from '@/components/UniAddressSelector.vue'
import Modal from '@/components/Modal.vue'
import Editor from '@/components/Editor/Editor.vue'
import CommonPopup from '@/components/CommonPopup.vue'
import env from '@/network/env.js'
import {
  ossUpload
} from '@/utils/jason-alioss-upload/oss.js'
import {
  userCardInfo,
  getClassAIndustry,
  getClassBIndustry,
  userRegister,
  userInfo,
  userUpdate,
  getPhone,
  registerJudge,
  phoneAreaCode,
  vcodeInter,
  sendCode,
  sendIntCode,
  userOutputList
} from '@/network/api.js'
import {
  debounce,
  hasEmptyValue
} from '@/utils/index.js'
export default {
  components: {
    Navbar,
    Bottom,
    IndustryPopup,
    UniAddressSelector,
    Modal,
    Editor,
    CommonPopup
  },
  data() {
    return {
      // 基础信息
      form: {
        head_img: '', // 头像
        name: '', // 名称
        area_code: '86', // 区号
        mobile: '', // 手机号
        company: '', // 公司名称
        position: '', // 职位
        province: '', // 省
        province_id: 0, // 省id
        city: '', // 市
        city_id: 0, // 市id
        hometown: '', // 省市区
        address: '', // 详细地址
        longitude: '', // 经度
        latitude: '' // 维度
      },
      cardForm: {
        id_card: '', // 身份证号
        industry: '', // 行业
        industry_id: '', // 行业
        product: '', // 产品
        specialty: '', // 特长
        tag: '', //标签
        hobby: '', // 爱好
        motto: '', // 座右铭
        resume: '', // 主要经历
        honor: '', // 荣誉
        company_des: '', // 企业简介
        personal_advantage: '', // 个人介绍
        recommend: '', // 引荐
        img_text: '', // 图集
        video_text: '', // 视频
        output: '', // 公司产值
      },
      headImgFileList: [],
      cardImgList: [],
      cardImgFileList: [], // 修改
      collapseList: [{
        head: "完善名片信息（非必填）",
        body: "",
        open: false
      }],
      // 注册表单字段（必不必填）
      judge: [],
      staff_number: '',
      fileList: [],
      headImg: '',
      visitCard: '',
      email: '',
      isEdit: 0,
      /* 0注册页面  1修改信息 */
      code: '9527',
      count: 0,
      codeStatus: true,
      actionOss: `${env.baseUrl}/api/uploadOssImage`,
      companyShow: false,
      companyList: [],
      /* 行业 */
      industryShow: false,
      classAIndustryList: [],
      classAIndustryObj: "",
      classBIndustryList: [],
      showUniAddressSelector: false,
      /* 新增 */
      customStyle: {
        background: '#F2F5FA',
        borderRadius: '20rpx',
        padding: '16rpx'
      },
      modal: {
        show: false,
        showCancel: true,
        confirmText: '申请',
        cancelText: '取消',
        content: ''
      },
      commonPopupData: {
        show: false,
        list: []
      },
      userInfo: {},
      agreement: false,
      unitObj: {},
      codeShow: false,
      codeList: [],
      btnText: '完善信息',
      params: ''

    }
  },
  onLoad(options) {
    if (options.isEdit) {
      this.isEdit = options.isEdit
      // this.agreement = true // 协议勾选状态
      this.btnText = '确认修改'
      this.collapseList[0].open = true
      this.handleGetUserInfo()
    }
    if (options.data) {
      this.params = JSON.parse(options.data)
    }

    this.handleGetOutputList()
    this.handleGetJudge()
    this.handleGetCountryCode()
    this.handleGetFirseIndustry()
  },
  methods: {
    async handleGetUserInfo() {
      /* 获取用户信息 */
      const res = await userInfo({
        user_id: uni.getStorageSync("user_id")
      })
      this.userInfo = res.data
      this.form.head_img = res.data.head_img
      this.headImgFileList = [{ url: res.data.head_img }]
      this.form.name = res.data.name
      this.form.mobile = res.data.phone
      // 省
      if (res.data.province_id) {
        this.form.province_id = res.data.province_id
        this.form.province = res.data.native.substring(0, res.data.native.indexOf("/"))
      }
      // 市
      if (res.data.city_id) {
        this.form.city_id = res.data.city_id
        this.form.city = res.data.native.substring(res.data.native.indexOf("/") + 1, res
          .data.native.indexOf("区") + 1)
      }
      // 完整城市
      if (res.data.province_id && res.data.city_id) {
        this.form.hometown = res.data.complete_address.substring(0, res.data.complete_address.lastIndexOf("区") + 1)
      }
      this.form.latitude = Number(res.data.latitude)
      this.form.longitude = Number(res.data.longitude)
      this.form.address = res.data.address
      this.form.company = res.data.company
      this.form.position = res.data.position

      const cardData = res.data.user_bussiness
      this.cardForm.id_card = res.data.id_card
      this.cardForm.industry = res.data.industry_names[0]
      this.cardForm.industry_id = res.data.industry_id
      this.cardForm.product = cardData.product || ''
      this.cardForm.specialty = cardData.specialty || ''
      this.cardForm.tag = cardData.tag || ''
      this.cardForm.hobby = cardData.hobby || ''
      this.cardForm.motto = cardData.motto || ''
      this.cardForm.resume = cardData.resume || ''
      this.cardForm.honor = cardData.honor || ''
      this.cardForm.company_des = cardData.company_des || ''
      this.cardForm.personal_advantage = cardData.personal_advantage || ''
      this.cardForm.recommend = cardData.recommend || ''
      this.cardForm.output = cardData.output || ''

      if (cardData.video_text[0]) {
        this.cardForm.video_text = cardData.video_text[0]
      }
      if (cardData.img_text[0]) {
        cardData.img_text.map(item => {
          const params = {
            url: item
          }
          this.cardImgFileList.push(params)
          this.cardImgList.push(item)
        })
      }
    },
    handleGetJudge() {
      registerJudge().then(res => {
        this.judge = res.data
      })
    },
    handleGetOutputList() {
      userOutputList().then(res => {
        this.commonPopupData.list = res.data
      })
    },
    handleGetCountryCode() {
      phoneAreaCode().then(res => {
        res.data.forEach(item => {
          item.label = item.name + '+' + item.area_code
        })
        this.codeList = res.data
      })
    },
    handleGetFirseIndustry() {
      /* 获取一级行业 */
      getClassAIndustry().then(res => {
        this.classAIndustryList = res.data
        this.classAIndustryObj = res.data[0]
        this.handleGetClassB(res.data[0].industry_id)
      })
    },
    handleCheckClassA(id) {
      /* 获取二级行业 */
      this.handleGetClassB(id)
    },
    handleGetClassB(id) {
      /* 行业确认选择 */
      getClassBIndustry({
        pid: id
      }).then(res => {
        this.classBIndustryList = res.data
      })
    },
    handleClosePopup(value) {
      this.form.industry_id = value.id
      this.cardForm.industry_id = value.id
      this.cardForm.industry = value.name
      this.industryShow = false
    },
    getPhoneNumber(e) {
      if (e.detail.errMsg !== 'getPhoneNumber:ok') {
        this.$u.toast("拒绝手机号登录");
        return;
      }
      getPhone({
        code: e.detail.code
      }).then(res => {
        this.form.area_code = res.data.phone_info.countryCode
        this.form.mobile = res.data.phone_info.purePhoneNumber
      })
    },
    goAgrement(type) {
      uni.navigateTo({
        url: '/operate/agreement/agreement?type=' + type
      })
    },
    onChooseAvatar(e) {
      /* 获取头像 */
      const avatarUrl = e.detail.avatarUrl
      const _this = this
      uni.uploadFile({
        filePath: avatarUrl,
        name: "file",
        url: _this.actionOss,
        success(res) {
          const {
            data
          } = JSON.parse(res.data)
          _this.form.head_img = data.url
        },
        fail(err) { }
      })
    },
    onSuccess(event) {
      /* 名片识别 */
      uni.showToast({
        icon: "loading",
        duration: 2500,
        title: "识别中",
      })
      const {
        data
      } = event
      userCardInfo({
        file_path: data.file_path
      }).then(res => {
        this.visitCard = res.data.imgUrl
        if (!this.form.name) {
          this.form.name = res.data.name
        }
        if (!this.form.mobile) {
          this.form.mobile = res.data.phone
        }
        if (!this.email) {
          this.email = res.data.email
        }
        if (!this.form.position) {
          this.form.position = res.data.position
        }
        if (!this.form.company) {
          this.form.company = res.data.company
        }
      })
    },
    onRemove() {
      this.visitCard = ''
      this.fileList.length = 0
    },
    openHomeTown() {
      this.showUniAddressSelector = true
    },
    handleCancel() {
      this.showUniAddressSelector = false;
    },
    handleConfirmArea(val) {
      this.showUniAddressSelector = false;
      this.form.province = val.provinceObj.areaName
      this.form.province_id = val.provinceObj.areaCode
      this.form.city = val.cityObj.areaName
      this.form.city_id = val.cityObj.areaCode
      this.form.hometown = val.fullAreaText
    },
    codeConfirm(val) {
      this.form.area_code = val[0].value
    },
    hanldeShowIndustry() {
      this.industryShow = true
    },
    hanldeShowOutPut() {
      this.commonPopupData.show = true
    },
    handleChooseLabel(val) {
      this.cardForm.output = val.name
      this.commonPopupData.show = false
    },
    handleSearchCompany: debounce(function (company) {
      const _this = this
      if (company) {
        uni.showLoading({
          title: '正在搜索中'
        })
        const params = {
          company_name: company[0]
        }
        const _this = this
        uni.request({
          url: `${env.baseUrl}/api/company_query_name`,
          method: "post",
          data: params,
          header: {
            'content-type': 'application/x-www-form-urlencoded',
            'Authorization': '',
          },
          success(res) {
            _this.companyShow = true
            _this.companyList = res.data.data.list;
            uni.hideLoading()
          }
        })
      }
    }, 1000),
    handleGetCompanyName(name) {
      this.form.company = name
      this.companyShow = false
    },
    handleGetLocation() {
      const _this = this
      uni.chooseLocation({
        success: function (res) {
          if (res.errMsg == 'chooseLocation:ok') {
            _this.form.address = res.name
            _this.form.latitude = res.latitude + Number(`0.000${Math.floor(Math.random() * 10)}`)
            _this.form.longitude = res.longitude + Number(`0.000${Math.floor(Math.random() * 10)}`)
          } else {
            uni.showToast({
              title: "地址获取失败，请重新获取",
              icon: "none"
            })
          }
        }
      })
    },
    onImageSuccess(val) {
      this.cardImgList.push(val.data.url)
    },
    onImageRemove(val) {
      this.cardImgList.splice(val, 1)
    },
    onHeadSuccess(val) {
      this.form.head_img = val.data.url
    },
    onHeadRemove(val) {
      this.form.head_img = ''
    },
    onBeforeUpload(index) {
      uni.showLoading({
        title: "上传中..."
      })
    },
    onSaveOne(val) {
      this.cardForm.resume = val.detail.__args__[0].html
    },
    onSaveTwo(val) {
      this.cardForm.honor = val.detail.__args__[0].html
    },
    onSaveThree(val) {
      this.cardForm.company_des = val.detail.__args__[0].html
    },
    onSaveFour(val) {
      this.cardForm.personal_advantage = val.detail.__args__[0].html
    },
    onSaveFive(val) {
      this.cardForm.recommend = val.detail.__args__[0].html
    },
    onUpdateVideo() {
      const _this = this
      uni.chooseVideo({
        sourceType: ['camera', 'album'],
        compressed: true,
        maxDuration: 10,
        success(res) {
          uni.showLoading({
            title: "文件上传中"
          })
          ossUpload(res.tempFilePath, res.tempFilePath, 'images/common/', '', res.tempFilePath
            .substring(res.tempFilePath.indexOf('.'))).then(ossRes => {
              if (ossRes.success == true) {
                _this.cardForm.video_text = ossRes.data
              }
              uni.hideLoading()
            })
        }
      })
    },
    confirm: debounce(function () {
      /* this.$refs.uForm.validate(valid => {
        if (valid) {
          this.onRequest()
        } else {
          console.log('验证失败');
        }
      }); */
      this.onRequest()
    }, 500),
    onRequest() {
      if (this.agreement) {
        //创建一个参数newform,里面不包含position和company
        let newform = { ...this.form }
        delete newform.position
        delete newform.company
        delete newform.head_img
        delete newform.address
        if (hasEmptyValue(newform)) {
          uni.showLoading({
            title: '提交中'
          });
          if (this.cardImgList[0]) {
            this.cardForm.img_text = this.cardImgList.join(',')
          }
          const params = {
            ...this.form,
            id_card: this.cardForm.id_card,
            complete_address: this.form.hometown + this.form.address,
            params: JSON.stringify(this.cardForm),
            open_id: uni.getStorageSync("openid")
          }
          let requl = userRegister
          if (this.isEdit == 1) {
            requl = userUpdate
            params.user_id = uni.getStorageSync("user_id")
          }
          requl(params).then(res => {
            uni.hideLoading()
            if (this.isEdit == 0) {
              uni.setStorageSync("user_status", res.data.status)
              uni.setStorageSync("token", res.data.token)
              uni.setStorageSync("user_id", res.data.id)
              uni.setStorageSync("user_phone", res.data.phone)
              uni.setStorageSync("user_name", res.data.name)
            }

            if (this.params) {
              uni.redirectTo({
                url: "/teaBureau/teaPointOrder/teaPointOrder?data=" + JSON.stringify(this.params)
              })
            } else {
              uni.redirectTo({
                url: "/teaBureau/teaPointOrder/teaPointOrder"
              })
            }
            
            // this.modal.show = true
            // this.modal.content = `${this.isEdit == 0 ? '注册成功' : '修改成功'}`
            // this.modal.confirmText = '确定'
          })
        } else {
          console.log(this.form)
          uni.showToast({
            title: "必填项不能为空",
            icon: "none"
          })
        }
      } else {
        uni.showToast({
          icon: "none",
          duration: 2000,
          title: "请先同意用户协议、隐私协议"
        })
      }
    },
    getCode() {
      if (this.codeStatus) {
        if (!this.form.mobile) {
          uni.showToast({
            title: "请输入手机号",
            icon: "none"
          })
          return
        }
        const params = {
          mobile: this.form.mobile,
          uid: uni.getStorageSync("user_id")
        }
        if (this.form.area_code == 86) {
          sendCode(params).then(res => {
            this.codeStatus = false
            uni.showToast({
              title: "发送成功",
              icon: "none"
            })
            this.count = 60
            const countDownInterval = setInterval(() => {
              this.count--
              if (this.count <= 0) {
                this.codeStatus = true
                clearInterval(countDownInterval)
              }
            }, 1000)
          })
        } else {
          params.area_code = this.form.area_code
          sendIntCode(params).then(res => {
            this.codeStatus = false
            uni.showToast({
              title: "发送成功",
              icon: "none"
            })
            this.count = 60
            const countDownInterval = setInterval(() => {
              this.count--
              if (this.count <= 0) {
                this.codeStatus = true
                clearInterval(countDownInterval)
              }
            }, 1000)
          })
        }
      } else {
        uni.showToast({
          title: "请勿重复点击",
          icon: "none"
        })
      }
    },
    modalConfirm() {
      this.modal.show = false
      let inviterUrl = uni.getStorageSync("inviterUrl")
      if (inviterUrl) {
        uni.setStorageSync("inviterUrl", "")
        uni.redirectTo({
          url: `/${inviterUrl}`
        })
      } else {
        uni.switchTab({
          url: "/pages/mine/mine"
        })
      }
    },
    modalCancel() {
      this.modal.show = false
      let pageUrl = getCurrentPages()[getCurrentPages().length - 2].route
      let inviterUrl = uni.getStorageSync("inviterUrl")
      if (inviterUrl && (pageUrl.includes('teaDetail') || pageUrl.includes('teaAgreement'))) {
        uni.setStorageSync("inviterUrl", "")
        uni.redirectTo({
          url: `/${inviterUrl}`
        })
      } else {
        uni.setStorageSync("inviterUrl", "")
        uni.switchTab({
          url: "/pages/mine/mine"
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.code_btn {
  background: #2C76ED;
  color: #fff;
  padding: 20rpx 20rpx;
  border-radius: 20rpx;
}

.code_box ::v-deep .u-input {
  width: 280rpx;
  margin-right: 20rpx;
}

.avatar-wrapper {
  color: #ffffff;
  background-color: #fb6316;
  margin-top: 20rpx;
}

.headImgBox {
  height: 100rpx;
  width: 100rpx;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
}

.company_btn {
  margin-left: 20rpx;
  margin-right: 0rpx;
  height: 70rpx;
  line-height: 70rpx;
  background: #fb6316;
  color: #fff;
  font-size: 26rpx;
}

.company_list {
  width: 100%;
  position: absolute;
  background-color: #868B9A;
  z-index: 10;
  padding: 0 10px;
  height: 320rpx;
  top: 100rpx;
  left: 0;
  overflow: auto;
  color: #fff;
  border-radius: 10rpx;
}

.editorTitle {
  font-size: 30rpx;
  font-weight: bold;
  color: #303133;
}

.editorBox {
  height: 100%;
  border-bottom: 1rpx solid #e4e7ed;
  padding-bottom: 40rpx;
}

#mobile_btn {
  padding: 0;
  margin: 0;
  text-align: right;
  background: transparent;
  font-size: 26rpx;
  flex: 1
}

#mobile_btn::after {
  border: none !important;
  height: 100%;
}

.u-text-right {
  line-height: 1.5;
}

::v-deep u-avatar {
  height: 100rpx !important;
}

::v-deep .u-input__textarea {
  line-height: normal;
}
</style>